package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    /**
     * 如何读取配置文件中的自定义配置？
     * 方案一：@Value
     * 方案二：Environment
     * 方案三：使用实体类 + @ConfigurationProperties (推荐方式)
     */
//    @Value("${minio.endpointUrl}")
//    private String endpointUrl ;

//    @Autowired
//    private Environment environment ;

    @Autowired
    private MinioConstantProperties constantProperties ;

    @Autowired
    private MinioClient minioClient ;

    @Override
    @SneakyThrows
    public String fileUpload(MultipartFile file) {

        // 创建bucket
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(constantProperties.getBucketName()).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(constantProperties.getBucketName()).build());
        }

        // 调用MinioClient对象中的方法完成文件的上传
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = file.getOriginalFilename();
        String fileExtName = FilenameUtils.getExtension(originalFilename);
        String fullFileName = fileName + "." + fileExtName ;

        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(constantProperties.getBucketName())         // 指定桶的名称
                .object(fullFileName)         // 指定文件名称
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        minioClient.putObject(putObjectArgs) ;

        // 拼接图片的访问地址
        String url = constantProperties.getEndpointUrl() + "/" + constantProperties.getBucketName() + "/" + fullFileName ;

        return url;
    }

}
